require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class IndividualPerformance
  
  NAME = "Individual Performance"
  

  def analyze(directory, experimentalData, phraseCards, normalize=true)
    
    #create the report
    reportname = normalize ? NAME + " (Normalized)" : NAME
    report = Report.new(directory, reportname )
    
    #get the data by uid    
    data = experimentalData.group_by_uid
        
    data.each_pair do |uid, entries|
      data_by_layer = {}
      
      entries.each do |e|
        #initialize if nil
        data_by_layer[e.layer] ||= []
        data_by_layer[e.layer] << e
      end
      
      #create a graph for each uid
      g = create_graph(uid)
      
      #do some simple statistics
      stat = ""
      
      #Generate a section for each tech layer
      data_by_layer.each_pair do |layer, entries|
         entries.sort! { |x,y| x.date <=> y.date }
         if normalize
          durations = entries.collect do |e|
            e.duration.to_f / phraseCards.getPhrase(e.set, e.phrase).length
          end
         else   
          durations = entries.collect {|e| e.duration}
         end
         avg = durations.inject{ |sum, el| sum + el }.to_f / durations.length  
         g.data "Layer:#{layer}", durations
         stat = stat + "<b>Layer #{layer}:</b> " +  
                "finished(phrases):#{entries.length} " +
                "average time: #{avg}" +
                (normalize ? " per character" : "") +
                "<br/>" 
      end
      
      report.new_section("Subject #{uid}", stat, g)  
        
    end

    #generate report  
    report.to_html
  end
  
  def create_graph (uid)
    g = Gruff::Line.new
    g.dot_radius = 2
    g.line_width = 2
    g.x_axis_label = "Phrases"
    g.y_axis_label = "Time (10 ms)"
    g.title = "Performance (UID:#{uid})"
    g
  end
  
end